// cloudfunctions/login/index.js
const https = require('https'); 
const cloud = require('wx-server-sdk');
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
});
const CryptoJS = require('crypto-js');
// const got = require('got');
// 封装 HTTP GET 请求
function httpsGet(url) {
    return new Promise((resolve, reject) => {
      https.get(url, (res) => {
        let data = '';
        res.on('data', (chunk) => data += chunk);
        res.on('end', () => resolve(JSON.parse(data)));
      }).on('error', (err) => reject(err));
    });
  }
exports.main = async (event, context) => {
    const {
        code,
        encryptedData,
        iv
    } = event;

    if (!code || !encryptedData || !iv) {
        throw new Error('缺少必要参数: code, encryptedData, iv');
    }

    const wxContext = cloud.getWXContext();
    const appid = wxContext.APPID;
    const secret = "909c4ba034274629a6341abaf92c90a7"; // 确保环境变量已配置

    // 调用接口换取 session_key 和 openid
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;

    const { openid, session_key, errcode, errmsg } = await httpsGet(url);
    console.log(session_key);
    console.log(encryptedData);
    console.log(iv);
    // 解密手机号
    const phoneData = decryptPhoneNumber(encryptedData, iv, session_key);
    return {
        code: 0,
        message: '登录成功',
        data: {
            openid,
            phoneNumber: phoneData.phoneNumber,
            purePhoneNumber: phoneData.purePhoneNumber,
            countryCode: phoneData.countryCode,
        }
    };
};

// // 手机号解密工具函数（增加异常处理）
function decryptPhoneNumber(encryptedData, iv, sessionKey) {
  try {
    if (!encryptedData || !iv || !sessionKey) {
      throw new Error('解密参数缺失');
    }

    const encryptedBase64 = CryptoJS.enc.Base64.parse(encryptedData);
    const keyBase64 = CryptoJS.enc.Base64.parse(sessionKey);
    const ivBase64 = CryptoJS.enc.Base64.parse(iv);

    const decipher = CryptoJS.AES.decrypt(
      { ciphertext: encryptedBase64 },
      keyBase64,
      {
        iv: ivBase64,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      }
    );

    const decoded = decipher.toString(CryptoJS.enc.Utf8);
    return JSON.parse(decoded);
  } catch (err) {
    console.error('解密错误:', err);
    throw new Error('手机号解密失败');
  }
}